﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;

public class UGUICreateSpriteAsset
{
    [MenuItem("Assets/Create/UGUI Sprite Asset",false,10)]
    static void main()
    {
        Object target = Selection.activeObject;
        if (target == null || target.GetType() != typeof(Texture2D))
            return;

        Texture2D sourceTex = target as Texture2D;
        //整体路径
        string filePathWithName = AssetDatabase.GetAssetPath(sourceTex);

        //带后缀的文件名
        string fileNameWithExtension = Path.GetFileName(filePathWithName);
        //不带后缀的文件名
        string fileNameWithOutExtension = Path.GetFileNameWithoutExtension(filePathWithName);
        //不带文件名的路径
        string filePath = filePathWithName.Replace(fileNameWithExtension, "");

        string assetPath = filePath + fileNameWithOutExtension + ".asset";
        UGUISpriteAsset spriteAsset = AssetDatabase.LoadAssetAtPath(assetPath, typeof(UGUISpriteAsset)) as UGUISpriteAsset;
        bool isNewAsset = spriteAsset == null;
        if (isNewAsset)
        {
            spriteAsset = ScriptableObject.CreateInstance<UGUISpriteAsset>();
            spriteAsset.textSource = sourceTex;
            spriteAsset.listSpriteAssetInfo = GetSpritesInfor(sourceTex);
            AssetDatabase.CreateAsset(spriteAsset, assetPath);
        }
    }

    /// <summary>
    /// 设置 sprites 具体信息
    /// </summary>
    private static List<SpriteAssetInfor> GetSpritesInfor(Texture2D tex)
    {
        List<SpriteAssetInfor> m_sprites = new List<SpriteAssetInfor>();

        string filePath = AssetDatabase.GetAssetPath(tex);

        Object[] objects = AssetDatabase.LoadAllAssetsAtPath(filePath);

        SpriteAssetInfor temp;
        Sprite sprite;
        for (int i = 0; i < objects.Length; i++)
        {
            if (objects[i].GetType() == typeof(Sprite))
            {
                temp = new SpriteAssetInfor();
                sprite = objects[i] as Sprite;
                temp.ID = i;
                temp.name = sprite.name;
                temp.pivot = sprite.pivot;
                temp.rect = sprite.rect;
                temp.sprite = sprite;

                m_sprites.Add(temp);
            }
        }
        return m_sprites;
    }
}
